package com.oa.ylms.apps.dao.regulations.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.constants.IDEDStates;
import com.oa.ylms.apps.dao.regulations.IRegulationCategoryDao;
import com.oa.ylms.apps.entity.regulations.RegulationCategoryValue;

public class RegulationCategoryDaoImpl extends HibernateDaoSupport implements IRegulationCategoryDao {

	private List<RegulationCategoryValue> list;
	
	@SuppressWarnings("unchecked")
	public List<RegulationCategoryValue> queryCategoryByStates(final RegulationCategoryValue regulationCategory) throws Exception {
		String hqlStr ="FROM RegulationCategoryValue rcv WHERE 1=1";
		if(regulationCategory.getStates() != null){
			hqlStr += " AND rcv.states = ?";
		}
		hqlStr += " AND rcv.states <> ?";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if(regulationCategory.getStates() != null){
					query.setInteger(++index, regulationCategory.getStates());
				}
				query.setInteger(++index, IDEDStates.DELETE);
				list = query.list();
				return list;
			}
		});
		return list;
	}


	public RegulationCategoryValue queryCategoryById(RegulationCategoryValue regulationCategory) throws Exception {
		System.out.println(regulationCategory.getCategoryId());

		if(regulationCategory!=null){
			return (RegulationCategoryValue) this.getHibernateTemplate().get(RegulationCategoryValue.class, regulationCategory.getCategoryId());
		}
		return null;
	}
	
	public int addNewsCategory(RegulationCategoryValue regulationCategory)throws Exception {
		if (regulationCategory != null) {
			this.getHibernateTemplate().save(regulationCategory);
			return regulationCategory.getCategoryId();
		}
		return 0;
	}

	public boolean editRegulationCategory(RegulationCategoryValue regulationCategory)throws Exception {
		if (regulationCategory != null) {
			try {
				this.getHibernateTemplate().update(regulationCategory);
				return true;
			} catch (Exception e) {
			}
		}
		return false;
	}


	public List<RegulationCategoryValue> getList() {
		return list;
	}


	public void setList(List<RegulationCategoryValue> list) {
		this.list = list;
	}
	
}
